package com.geeklan.smart.ui.pet;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.R;
import com.geeklan.smart.databinding.ActivityAddPetBinding;
import com.geeklan.smart.permission.PermissionManager;
import com.geeklan.smart.ui.pet.adapter.PhotoAdapter;
import com.geeklan.smart.utils.DialogUtils;
import com.geeklan.smart.utils.GlideEngine;
import com.geeklan.smart.utils.ImagePathUtils;
import com.geeklan.smart.widget.GridSpacingItemDecoration;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.List;

import gun0912.tedimagepicker.builder.TedImagePicker;

public class AddPetActivity extends BaseActivity<ActivityAddPetBinding> implements PhotoAdapter.PhotoAdapterListener {
    private PhotoAdapter photoAdapter;
    private ArrayList<String> pathList = new ArrayList<>();
    private String headUri;
    private boolean isHead;
    private String etPetName;
    @Override
    protected ActivityAddPetBinding initBinding() {
        return ActivityAddPetBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        mBinding.ivBack.setOnClickListener(v -> finish());
        photoAdapter = new PhotoAdapter(this, pathList, this);

        mBinding.rvPhotos.setLayoutManager(new GridLayoutManager(this, 4)); // 网格布局，3列
        mBinding.rvPhotos.addItemDecoration(new GridSpacingItemDecoration(10));
        mBinding.rvPhotos.setAdapter(photoAdapter);
        mBinding.tvNext.setOnClickListener(v -> {
//            for (Uri uri : photoList) {
//                pathList.add(ImagePathUtils.getImagePath(this, uri));
//            }
            etPetName = mBinding.etPetName.getText().toString();
            if(headUri == null) {
                Toast.makeText(this,"请添加宠物头像",Toast.LENGTH_SHORT).show();
                return;
            }

            if(TextUtils.isEmpty(etPetName)) {
                Toast.makeText(this,"请输入宠物名称",Toast.LENGTH_SHORT).show();
                return;
            }

            if(etPetName.length() > 20) {
                Toast.makeText(this,"宠物名称不能超过20字",Toast.LENGTH_SHORT).show();
                return;
            }

            SelectPetActivity.startActivity(this, pathList, headUri, etPetName);
        });
        mBinding.ivPetHead.setOnClickListener(v -> {
            isHead = true;
            checkAndRequestPermissions();
        });
        mBinding.textView1.setText(String.format(getString(R.string.pet_photo_number),pathList.size()));
    }

    private void showSelectPhotoDialog() {
        DialogUtils.showSelectDialog(this, v -> {
            if (isHead) {
                PictureSelector.create(this)
                        .openGallery(SelectMimeType.ofImage()) // 选择图片
                        .setImageEngine(GlideEngine.createGlideEngine()) // 使用 Glide 加载图片
                        .setMaxSelectNum(1)
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                // 处理返回的图片
                                for (LocalMedia media : result) {
                                    headUri = media.getRealPath();
                                    Glide.with(AddPetActivity.this).load(media.getRealPath()).apply(RequestOptions.circleCropTransform()).into(mBinding.ivPetHead);
                                }
                            }
                            @Override
                            public void onCancel() {}
                        });

            } else {
                PictureSelector.create(this)
                        .openGallery(SelectMimeType.ofImage()) // 选择图片
                        .setImageEngine(GlideEngine.createGlideEngine()) // 使用 Glide 加载图片
                        .setMaxSelectNum(10 - pathList.size())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                // 处理返回的图片
                                for (LocalMedia media : result) {
                                    int size = pathList.size() - 1;
                                    pathList.add(media.getRealPath());
                                    photoAdapter.notifyItemChanged(size, pathList.size() - 1);
                                    mBinding.textView1.setText(String.format(getString(R.string.pet_photo_number),pathList.size()));
                                }
                            }
                            @Override
                            public void onCancel() {}
                        });
            }
        }, v -> {
            if (isHead) {
                PictureSelector.create(this)
                        .openCamera(SelectMimeType.ofImage()) // 拍照
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                for (LocalMedia media : result) {
                                    headUri = media.getRealPath();
                                    Glide.with(AddPetActivity.this).load(media.getRealPath()).apply(RequestOptions.circleCropTransform()).into(mBinding.ivPetHead);
                                }
                            }
                            @Override
                            public void onCancel() {}
                        });

            } else {
                PictureSelector.create(this)
                        .openCamera(SelectMimeType.ofImage()) // 拍照
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                for (LocalMedia media : result) {
                                    int size = pathList.size() - 1;
                                    pathList.add(media.getRealPath());
                                    photoAdapter.notifyItemChanged(size, pathList.size() - 1);
                                    mBinding.textView1.setText(String.format(getString(R.string.pet_photo_number),pathList.size()));
                                }
                            }
                            @Override
                            public void onCancel() {}
                        });
            }
        });
    }

    private void checkAndRequestPermissions() {
        if (!PermissionManager.hasPermissions(this, PermissionManager.REQUIRED_PERMISSIONS)) {
            requestPermissions(PermissionManager.REQUIRED_PERMISSIONS, PERMISSION_REQ_ID);
        } else {
            showSelectPhotoDialog();
        }
    }

    @Override
    public void onPermissionsResultSuccess() {
        super.onPermissionsResultSuccess();
        showSelectPhotoDialog();
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, AddPetActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    @Override
    public void onAddPhotoClick() {
        // 添加图片逻辑
        if (pathList.size() < 10) {
            isHead = false;
            checkAndRequestPermissions();
        } else {
            Toast.makeText(AddPetActivity.this, "最多只能添加10张图片", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDeletePhotoClick(int position) {
        // 删除图片逻辑
        int actualPosition = position - (pathList.size() < 10 ? 1 : 0);
        pathList.remove(actualPosition);
        mBinding.textView1.setText(String.format(getString(R.string.pet_photo_number),pathList.size()));
        photoAdapter.notifyDataSetChanged();
    }
}